/**
 * 功能权限管理管理
 *
 * Created by piandu
 * Date 2018/05/11
 */
var scripts = [null,
    ctx + '/resource/plugins/ace/components/jqGrid/js/jquery.jqGrid.js',
    ctx + '/resource/plugins/ace/components/jqGrid/js/i18n/grid.locale-cn.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.zh-CN.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/bootstrapValidator.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/language/zh_CN.js',
    ctx + '/resource/plugins/jquery.jqGrid.patch.src.js',
    ctx + '/resource/plugins/ace/components/_mod/fuelux/tree.js',
    ctx + '/resource/plugins/ace/assets/js/src/elements.treeview.js',
    ctx + '/resource/utils/roleTreeData.js',
    ctx + '/resource/utils/roleMenuTreeData.js',
    null];
pageContentArea.ace_ajax('loadScripts', scripts, function () {


    jQuery(function ($) {
        // 初始化树
        $('#roleTreeview').ace_tree({
            dataSource: remoteRoleDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': false,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        }).on('selected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        }).on('deselected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        }).on('closed.fu.tree', function (event, data) {
            reloadJqGrid('json');
        });

        // 默认展开根节点
        $('#roleTreeview').tree('openFolder', $('#roleTreeview').find('.tree-branch')[1]);

        var grid_selector = '#grid-table';
        var $grid_selector = $(grid_selector);
        var pager_selector = '#grid-pager';
        var parent_column = $grid_selector.closest('[class*="col-"]');
        var colNames = [
            '角色编码',
            '角色名称',
            '菜单编码',
            '菜单名称',
        ];
        var fullWidth = pageContentArea.width();
        var width = pageContentArea.width() / colNames.length;
        var colModels = [
            {name: 'roleCode', index: 'roleCode', hidden: true},
            {name: 'roleName', index: 'roleName', hideWidth: 650, width: width},
            {name: 'moduleCode', index: 'moduleCode', hideWidth: 300, width: width},
            {name: 'moduleName', index: 'moduleName', hideWidth: 650, width: width},
        ];

        $grid_selector.jqGrid({
            url: ctx + '/tbSysRoleModule/queryPageList',
            mtype: 'post',
            datatype: 'json',
            height: '100%',
            colNames: colNames,
            colModel: colModels,
            autowidth: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: rowNum,
            rowList: rowList,
            pager: pager_selector,
            sortname: 'moduleCode',
            sortorder: 'asc',
            jsonReader: jsonReader,
            beforeRequest: function () {
                var postData = {};
                $('#queryPanel').find('[name^="search."]').each(function () {
                    var $this = $(this);
                    postData[$this.attr('name').replace(/search\./, '')] = $this.val();
                });
                // 获取角色树节点
                var selectedItems = $('#roleTreeview').tree('selectedItems');
                if (isNotEmpty(selectedItems)) {
                    postData['roleCode'] = selectedItems[0].additionalParameters.id;
                } else {
                    postData['roleCode'] = null;
                }
                $.extend($grid_selector.getGridParam('postData'), postData);
            },
            loadComplete: function () {
                setTimeout(function () {
                    $grid_selector.jqGrid('setGridWidth', parent_column.width());
                }, 20);
            }
        });

        //navButtons
        $grid_selector.jqGrid('navGrid', pager_selector, {
            add: false, edit: false, del: false, search: false, view: false, refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green'
        }).navSeparatorAdd(pager_selector, {
            sepclass: 'ui-separator',
            sepcontent: ''
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '导出Excel',
            buttonicon: 'ace-icon fa fa-file-excel-o green',
            onClickButton: expRowsToExcel,
            position: 'last'
        });

        $('#addMenuBtn').click(function () {
            $('#roleMenuTreeview').tree('destroy');
            $('#treeDiv').html('<ul id="roleMenuTreeview"></ul>');
            var selectedItems = $('#roleTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                var roleCode = selectedItems[0].additionalParameters.id;
                $.launchDialog('addMenuModal');
                $('#roleMenuTreeview').ace_tree({
                    dataSource: remoteRoleMenuDateSource,
                    loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
                    'cacheItems': true,
                    'open-icon': 'ace-icon fa fa-chevron-down',
                    'close-icon': 'ace-icon fa fa-chevron-right',
                    'itemSelect': true,
                    'folderSelect': true,
                    'multiSelect': true,
                    'selected-icon': null,
                    'unselected-icon': null,
                    'folder-open-icon': 'ace-icon tree-plus',
                    'folder-close-icon': 'ace-icon tree-minus'
                });
                $.ajax({
                    async: false,
                    type: 'post',
                    url: ctx + '/tbSysRoleModule/queryList',
                    dataType: 'json',
                    data: {
                        roleCode: roleCode
                    },
                    success: function (data) {
                        $('#roleMenuTreeview').tree('discloseAll');
                        for (var i = 0; i < data.length; i++) {
                            var idStr = '#' + data[i].moduleCode;
                            $('#roleMenuTreeview').tree('selectItem', $('#roleMenuTreeview ' + idStr));
                        }

                        // 初始化已选择的权限后，增加父节点的选中事件
                        $('#roleMenuTreeview').on('selected.fu.tree', function (event, data) {
                            var children = data.target.additionalParameters.children;
                            $.each(children, function (idx, item) {
                                // if (item.type == 'item' && item.additionalParameters['item-selected'] == false) {
                                    var itemId = '#' + item.additionalParameters.id;
                                    $('#roleMenuTreeview').tree('selectItem', $(itemId));
                                // }
                            });
                        }).on('deselected.fu.tree', function (event, data) {
                            // do something with data: { selected: [array], target: [object] }
                        })
                    }
                });

            } else {
                $(this).dynamicPop('请选择角色！');
            }
        });

        $('#saveMenuBtn').click(function () {
            //显示遮罩
            $("#runningModal").modal('show');
            //使点击空白处遮罩层不会消失
            $("#runningModal").modal({backdrop: 'static'});
            //按Tab键遮罩层不会消失 ，默认值为true
            $("#runningModal").modal({keyboard: false});
            var roleSelectedItems = $('#roleTreeview').tree('selectedItems');
            var roleCode = roleSelectedItems[0].additionalParameters.id;
            var menuSelectedItems = $('#roleMenuTreeview').tree('selectedItems');
            var moduleCodes = new Array();
            for (var i = 0; i < menuSelectedItems.length; i++) {
                moduleCodes[i] = menuSelectedItems[i].additionalParameters.id;
            }
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbSysRoleModule/save',
                dataType: 'json',
                data: {
                    roleCode: roleCode,
                    moduleCode: moduleCodes.join(',')
                },
                success: function (data) {
                    if (data) {
                        $('#roleMenuTreeview').tree('destroy');
                        $('#treeDiv').html('<ul id="roleMenuTreeview"></ul>');
                        // 关闭窗口
                        $('#addMenuModal').modal('hide');
                        //隐藏遮罩
                        $('#runningModal').modal('hide');
                        // 删除成功将表格刷新
                        reloadJqGrid('json');
                    }
                }
            });
        });


        var grid_func_selector = '#grid-func-table';
        var $grid_func_selector = $(grid_func_selector);
        var parent_column_func = $grid_func_selector.closest('[class*="col-"]');
        var colNamesFunc = [
            '主键ID',
            '字典值',
            '字典所属分类',
            '显示排序'
        ];
        var widthFunc = parent_column_func.width() / colNamesFunc.length;

        var colModelsFunc = [
            {name: 'id', index: 'id', hidden: true},
            {name: 'dictValue', index: 'dictValue', hidden: true},
            {name: 'dictClassify', index: 'dictClassify', hidden: true},
            {name: 'viewOrder', index: 'viewOrder', hidden: true}
        ];

        $grid_func_selector.jqGrid({
            url: ctx + '/tbCmdbDict/queryPageList',
            mtype: 'post',
            datatype: 'local',
            height: '100%',
            colNames: colNamesFunc,
            colModel: colModelsFunc,
            autowidth: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: 20,
            // rowList: rowList,
            // pager: pager_selector,
            sortname: 'viewOrder',
            sortorder: 'asc',
            jsonReader: jsonReader,
            beforeRequest: function () {
                $.extend($grid_func_selector.getGridParam('postData'), {'dictClassify': 'func_authorization'});
            },
            loadComplete: function () {
                setTimeout(function () {
                    $grid_func_selector.jqGrid('setGridWidth', parent_column_func.width());
                }, 20);
            }
        });


        $('#addFunctionBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的记录!');
            } else if (rowIds.length == 1) {
                $grid_func_selector.jqGrid('setGridParam', {datatype: 'json'}).trigger('reloadGrid');
                // // 弹出模态框
                $.launchDialog('addFunctionModal');
            } else {
                $('#addFunctionModal').find("input:checkbox").removeAttr("checked");
                // 弹出模态框
                $.launchDialog('addFunctionModal');
            }
        });

        $('#saveFunctionBtn').click(function () {
            // 获取roleCode、menuCode
            var roleCode;
            var moduleCodes = new Array();

            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                roleCode = $grid_selector.jqGrid('getRowData', rowId).roleCode;
                moduleCodes[0] = $grid_selector.jqGrid('getRowData', rowId).menuCode;
            } else {
                for (var i = 0; i < rowIds.length; i++) {
                    if (i == 0) {
                        roleCode = $grid_selector.jqGrid('getRowData', rowIds[i]).roleCode;
                    }
                    moduleCodes[i] = $grid_selector.jqGrid('getRowData', rowIds[i]).menuCode;
                }
            }
            // 获取功能权限
            var permissions = new Array();

            var rowFuncIds = $grid_func_selector.jqGrid('getGridParam', 'selarrrow');

            if (rowFuncIds == null || rowFuncIds.length == 0) {
                $('#saveFunctionBtn').dynamicPop('请选择功能权限！');
            } else {
                for (var i = 0; i < rowFuncIds.length; i++) {
                    permissions[i] = $grid_func_selector.jqGrid('getRowData', rowFuncIds[i]).dictValue;
                }
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbSysRoleModule/save',
                    dataType: 'json',
                    data: {
                        roleCode: roleCode,
                        moduleCodes: moduleCodes.join(','),
                        permissions: permissions.join(',')
                    },
                    success: function (data) {
                        if (data) {
                            // 关闭窗口
                            $('#addFunctionModal').modal('hide');
                            // 删除成功将表格刷新
                            reloadJqGrid('json');
                        }
                    }
                });
            }


        });

        // 导出excel
        function expRowsToExcel() {
            var colFieldViewNames = new Array();
            var colFieldNames = new Array();
            $.each(colModels, function (idx, obj) {
                if (obj.hidden == false || obj.hidden == undefined) {
                    colFieldNames.push(obj.index);
                    colFieldViewNames.push(colNames[idx]);
                }
            });
            var sortName = $grid_selector.jqGrid('getGridParam', 'sortname');// 排序列
            var sortOrder = $grid_selector.jqGrid('getGridParam', 'sortorder');// 排序方式：desc、asc
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            postData.titles = colFieldViewNames;
            postData.fields = colFieldNames;
            postData.sidx = sortName;
            postData.sord = sortOrder;
            // 获取角色树节点
            var selectedItems = $('#roleTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                postData['roleCode'] = selectedItems[0].additionalParameters.id;
            } else {
                postData['roleCode'] = null;
            }
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbSysRoleModule/expExcel',
                dataType: 'json',
                data: postData,
                success: function (data) {
                    downloadFile(data.result);// 下载文件
                }
            });
        }

        // 重新加载jqGrid表格
        function reloadJqGrid(datatype) {
            $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
        }

        // 显示隐藏查询条件
        $('#searBtn').click(function () {
            $(this).find('i').toggleClass('fa-arrow-down');
            $(this).find('i').toggleClass('fa-arrow-up');
        });

        $('#searchBtn').click(function () {
            $grid_selector.trigger('reloadGrid', [{page: 1}]);
        });

        // 重置查询表单
        $('#resetBtn').click(function () {
            $('#queryPanel').find(':input(:text)').each(function () {
                $(this).val('');
            });
            $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
                $(this).removeAttr('checked');
            });
            reloadJqGrid('json');
        });

        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });

        $('.input-daterange').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            //todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        });

        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $grid_selector.jqGrid('setGridWidth', parent_column.width());
        });

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });


        $(document).on('show.bs.modal', function () { // 在调用 show 方法后触发。
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 1);
        }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
            setTimeout(function () {
                $grid_func_selector.jqGrid('setGridWidth', parent_column_func.width());
            }, 1);
        });
    });

});
